<template>
  <div class="chart-item-container">
    <div v-if="carStatisticsamount?.carCountDto?.length > 0" ref="storeInventory" class="chart-item"></div>
    <div v-else class="empty">
      <img class="empty-img" src="../../../../assets/empty-store.png" />
      <div class="empty-text">暂无门店数据</div>
    </div>
  </div>
</template>
<script lang="ts">
  import useEcharts from '@/hooks/useEcharts'
  import { defineComponent, nextTick, onBeforeUnmount, onMounted, ref, watch } from 'vue'
  import { dispose } from 'echarts/core'
  const xaxisdata: any[] = []
  const yaxisdata: number[] = []

  let dataCount: any[] = []
  let dataOutboundCount: any[] = []

  const els = document.getElementsByClassName('tooltip-radio')

  const onClickCar = (el: any, type: string) => {
    for (let i = 0; i < els.length; i++) {
      els[i].classList.remove('tooltip-active')
    }
    el.classList.add('tooltip-active')

    const series = document.getElementById('series')
    const model = document.getElementById('model')
    if (type === 'series') {
      series?.classList.add('tooltip-block')
      series?.classList.remove('tooltip-none')

      model?.classList.add('tooltip-none')
      model?.classList.remove('tooltip-block')
    } else {
      series?.classList.add('tooltip-none')
      series?.classList.remove('tooltip-block')

      model?.classList.add('tooltip-block')
      model?.classList.remove('tooltip-none')
    }
  }
  window['onClickCar'] = onClickCar

  export default defineComponent({
    name: 'StoreInventory',
    props: {
      carStatisticsamount: {
        type: Object,
      },
    },
    setup(props) {
      const loading = ref(true)
      const storeInventory = ref<HTMLDivElement | null>(null)
      const baramount = ref<any[]>([])
      const init = () => {
        dataCount = props.carStatisticsamount?.carCountDto?.map((item: any) => item.count)
        dataOutboundCount = props.carStatisticsamount?.carCountDto?.map((item: any) => item.outboundCount)
        const option = {
          color: ['#1890FF'],
          grid: {
            top: '10%',
            left: '1%',
            right: '2%',
            bottom: '5%',
            containLabel: true,
          },
          tooltip: {
            trigger: 'axis',
            triggerOn: 'click',
            enterable: true,
            appendTo: 'body',
            formatter(params: any) {
              const amount = baramount.value[params[0].dataIndex]
              console.log('amount', amount)

              let str = `
              <div class="tooltip-title flexable">
                <span class="whitespace" title="${amount.siteName}">
                  ${amount.siteName}
                </span>
                <span>共${amount.count}辆</span>
              </div>
              <div class="tooltip-radio-group flex">
                <div class="tooltip-radio tooltip-active flex justify-center items-center px-2" onclick="onClickCar(this, 'series')">
                  车系维度统计
                </div>
                <div class="tooltip-radio flex justify-center items-center px-2" onclick="onClickCar(this, 'model')">
                  车型维度统计
                </div>
              </div>
              <div class="content-box">
              `

              str += '<div id="series" class="tooltip-block">'
              // 车系
              for (var i = 0; i < amount.carSeriesInfoDto.length; i++) {
                str += `
                <div class="content-panel">
                  <div class="whitespace" title="${amount.carSeriesInfoDto[i].seriesName}">
                    ${amount.carSeriesInfoDto[i].seriesName}
                  </div>
                  <div class="tooltip-value">${amount.carSeriesInfoDto[i].count}辆</div>
                </div>`
              }
              str += '</div>'

              str += '<div id="model" class="tooltip-none">'
              // 车型
              for (var i = 0; i < amount.carModelInfoDto.length; i++) {
                str += `
                <div class="content-panel">
                  <div class="whitespace" title="${amount.carModelInfoDto[i].modelName}">
                    ${amount.carModelInfoDto[i].modelName}
                  </div>
                  <div class="tooltip-value">${amount.carModelInfoDto[i].count}辆</div>
                </div>`
              }
              str += '</div>'

              return '<div class="tooltip-box">' + str + '</div></div>'
            },
            className: 'echarts-tooltip-diy',
          },
          xAxis: {
            type: 'category',
            data: xaxisdata,
            axisLabel: {
              interval: 0,
              fontSize: 10,
              color: '#86909C',
              padding: [5, 0, 0, 0],
              formatter: function (value: any) {
                // 自定义换行逻辑，这里以每两个字符换行为例
                return value
              },
            },
            axisLine: {
              show: true,
              lineStyle: {
                color: '#E5E8EF',
              },
            },
          },
          yAxis: {
            type: 'value',
            name: '单位(辆)',
            minInterval: 1,
            nameTextStyle: {
              //  单位样式
              color: '#4E5969', //  字体颜色
              fontSize: 8, //  字体大小
              padding: [0, 18, 0, 0],
            },
            axisLabel: {
              fontSize: 10,
              color: '#4E5969',
            },
            axisLine: {
              show: true,
              lineStyle: {
                color: '#F2F3F5',
                width: 0,
                type: 'solid',
              },
            },
          },
          dataZoom: [
            {
              type: 'slider',
              realtime: true,
              // start: 0,
              // end: 20,  // 数据窗口范围的结束百分比。范围是：0 ~ 100。
              height: 5, //组件高度
              left: '10%', //左边的距离
              right: '10%', //右边的距离
              bottom: '0%', //下边的距离
              show: xaxisdata.length > 3 ? true : false, // 是否展示
              fillerColor: 'rgba(2,110,252,1)', // 滚动条颜色
              borderColor: 'rgba(17, 100, 210, 0.12)',
              backgroundColor: 'rgba(232,244,255,0.51)', //两边未选中的滑动条区域的颜色
              handleSize: 0, //两边手柄尺寸
              showDetail: false, //拖拽时是否展示滚动条两侧的文字
              zoomLock: true, //是否只平移不缩放
              moveOnMouseMove: false, //鼠标移动能触发数据窗口平移
              startValue: 0, // 从头开始。
              endValue: 10, // 最多5个
            },
            {
              type: 'inside', // 支持内部鼠标滚动平移
              start: 0,
              startValue: 0, // 从头开始。
              endValue: 10, // 最多10个
              zoomOnMouseWheel: false, // 关闭滚轮缩放
              moveOnMouseWheel: true, // 开启滚轮平移
              moveOnMouseMove: true, // 鼠标移动能触发数据窗口平移
            },
          ],
          series: [
            {
              name: '周销售图',
              type: 'bar',
              barWidth: 28,
              color: '#1890FF ',
              data: dataCount,
              label: {
                //柱体上显示数值
                show: true, //开启显示
                position: 'top',
                textStyle: {
                  //数值样式
                  fontSize: '10px',
                  color: '#666',
                  textAlign: 'center',
                },
                formatter: (params: any) => dataOutboundCount[params.dataIndex] + '/' + params.value,
              },
            },
            {
              name: '周销售图',
              type: 'bar',
              barWidth: 28,
              color: '#8EC9FF',
              barGap: '-100%',
              data: dataOutboundCount,
              label: {
                //柱体上显示数值
                show: true, //开启显示
                position: ['10%', '6%'],
                textStyle: {
                  //数值样式
                  fontSize: '10px',
                  color: '#000',
                  textAlign: 'center',
                },
                formatter: (params: any) =>
                  dataCount[params.dataIndex] != 0 ? Math.round((params.value / dataCount[params.dataIndex]) * 100) + '%' : '0%',
              },
            },
          ],
        }
        loading.value = false
        nextTick(() => useEcharts(storeInventory.value as HTMLDivElement)?.setOption(option))
      }
      const updateChart = () => {
        useEcharts(storeInventory.value as HTMLDivElement)?.resize()
      }
      onMounted(() => {
        init()
        window.addEventListener('resize', () => {
          useEcharts(storeInventory.value as HTMLDivElement)?.resize()
        })
        console.log('props.carStatisticsamount', props.carStatisticsamount)
      })
      watch(
        () => props.carStatisticsamount,
        (value) => {
          if (value?.carCountDto) {
            if (xaxisdata.length > 0) {
              xaxisdata.splice(0, xaxisdata.length)
              yaxisdata.splice(0, yaxisdata.length)
            }
            baramount.value = value.carCountDto
            value.carCountDto.forEach((item: any) => {
              let siteName = item.siteName
              let arr = siteName.split('')
              if (item.siteName.length > 4) {
                siteName = arr.splice(4, 0, '\n')
              }
              siteName = arr.join('')
              xaxisdata.push(siteName)
              yaxisdata.push(item.count)
            })
            init()
          }
        },
        { immediate: true, deep: true }
      )

      onBeforeUnmount(() => {
        if (storeInventory.value) {
          dispose(storeInventory.value as HTMLDivElement)
        }
      })
      return {
        loading,
        storeInventory,
        updateChart,
      }
    },
  })
</script>

<style lang="less">
  .tooltip-box {
    max-height: 257px;
    display: flex;
    flex-direction: column;
    overflow: hidden;

    .content-box {
      overflow: auto;
    }
  }
  .tooltip-block {
    display: block;
  }
  .tooltip-none {
    display: none;
  }
  .tooltip-radio-group {
    margin-bottom: 8px;
    .tooltip-radio {
      height: 20px;
      font-weight: 400;
      font-size: 12px;
      color: #1890ff;
      border-radius: 999px 999px 999px 999px;
      border: 1px solid #1890ff;
      cursor: pointer;
      margin-right: 16px;

      &.tooltip-active {
        background-color: #1890ff;
        color: #fff;
      }
    }
  }
</style>

<style lang="less" scoped>
  .chart-item-container {
    width: 100%;
    height: 260px;
    .chart-item {
      height: 100%;
    }
  }
  .empty {
    width: 100%;
    height: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
    flex-direction: column;
    .empty-img {
      display: inline-block;
      width: 110px;
    }
    .empty-text {
      font-size: 14px;
      font-family: PingFang SC, PingFang SC;
      font-weight: 400;
      color: #9ea5bb;
      line-height: 22px;
      margin-top: 16px;
    }
  }
</style>
